package shaw.wifi.server;

import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.PrintStream;
import java.sql.Timestamp;
import java.util.ArrayList;

import shaw.wifi.Constants;

public class ClientConnectionManager {
	private static PrintStream logStream;
	public static void log(long msTime, String s) {
		Timestamp ts = new Timestamp(msTime);
		logStream.println(ts + " :: " + s);
		System.out.println(ts + " :: " + s);
	}
	static {
		try {
			logStream = new PrintStream(new FileOutputStream("ssc.log"));
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		}
	}
	
	class ManagedConnection {
		public ClientConnection connection;
		public long time;
		public int messages;
		
		public ManagedConnection(ClientConnection c) {
			connection = c;
			time = System.currentTimeMillis();
			log(time, "New connection recieved (" + connections.size() + " connections)");
		}
	}
	
	private ArrayList<ManagedConnection> connections = new ArrayList<ManagedConnection> ();
	public int register(ClientConnection clientConnection) {
		ManagedConnection mc = new ManagedConnection(clientConnection);
		connections.add(mc);
		
		return connections.size() - 1;
	}
	
	public ClientConnectionManager() {
		Thread t = new Thread(new Update());
		//t.start();
	}
	
	public class Update implements Runnable {
		private boolean skip = false;
		private ManagedConnection target = null;
		@Override	
		public void run() {
			while(true) {
				try {
					if(skip == false) {
						Thread.sleep(1000);
					}
					skip = false;
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
				
				long t = System.currentTimeMillis();
				for(ManagedConnection mc: connections) {
					if(t-mc.time > 1000 * Constants._CONNECTIONTIMEOUT) {
						target = mc;
						break;
					}
				}
				
				if(target != null) {
					skip = true;
					target.connection.timeout();
					connections.remove(target);
					System.out.println(connections.size());
				}	
			}
		}
	}

	public void close(ClientConnection clientConnection) {
		int index = getConnectionIndex(clientConnection);
		if(index == -1) return;
		connections.remove(index);
	}

	private int getConnectionIndex(ClientConnection cc) {
		for(ManagedConnection mc : connections) {
			if(mc.connection == cc) {
				return connections.indexOf(mc);
			}
		}
		return -1;
	}
	public void recieveMessage(ClientConnection clientConnection) {
		int index = getConnectionIndex(clientConnection);
		if(index == -1) {
			clientConnection.timeout();
		}
		ManagedConnection mc = connections.get(index);
		mc.messages++;
		String timeDiff = String.valueOf(System.currentTimeMillis()-mc.time) + "ms)";
		String msg = "recieved message from " + index + " (" + mc.messages + " in " + timeDiff;
		log(System.currentTimeMillis(), msg);
	}
}
